import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

import java.io.IOException;

class NettyClientHandlerInner extends ChannelInboundHandlerAdapter {
    ChannelHandlerContext ctxOut;
    //通道就绪事件(就是在bootstrap启动助手配置中addlast了handler之后就会触发此事件)
    //但我觉得也可能是当有客户端连接上后才为一次通道就绪
    public void channelActive(ChannelHandlerContext ctx) throws IOException, InterruptedException {
        System.out.println("客户端消息，通道激活，可以发送消息了");
        ctxOut=ctx;

    }

    //数据读取事件
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        //传来的消息包装成字节缓冲区
        String byteBuf = (String) msg;
//        ByteBuf byteBuf = (ByteBuf) msg;
        //Netty提供了字节缓冲区的toString方法，并且可以设置参数为编码格式：CharsetUtil.UTF_8
        System.out.println("客户端读取服务返回的数据：" + byteBuf);
    }

    public void  sendMSG(String msg){
        ctxOut.writeAndFlush(Unpooled.copiedBuffer(msg+"\r\n", CharsetUtil.UTF_8));
    }

        @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);

        System.out.println("与服务器断开");

        ctx.channel().eventLoop().schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("234234");
//                nettyClient1.doReconnect();
                nettyClient1.doReconnect();
            }
        }, 3, TimeUnit.SECONDS);

        System.out.println("与服务器断开123123");
        ctx.close();
    }
}